﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.IO;
using System.Data.SqlClient;

namespace cms
{
    public partial class Setup : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ui_btnBuildDatabase_Click(object sender, EventArgs e)
        {
            Button dbButton = sender as Button;
            string connection = null;
            string scriptPath = "~/app_data/";

            if(dbButton.ID == "ui_btnCMSDatabase")
            {
                connection = ConfigurationManager.ConnectionStrings[ui_txtCMSConnection.Text].ConnectionString;
                scriptPath += "db1.sql";
            }
            else if(dbButton.ID == "ui_btnMembersDatabase")
            {
                connection = ConfigurationManager.ConnectionStrings[ui_txtMembersConnection.Text].ConnectionString;
                scriptPath += "db1Members.sql";
            }
            if (connection == null)
                throw new Exception("Could not find the connection information.");
            else
                BuildDatabase(connection, scriptPath);
        }

        private void BuildDatabase(string connection, string scriptPath)
        {
            StreamReader scriptReader = File.OpenText(Server.MapPath(scriptPath));
            string sql = scriptReader.ReadToEnd();
            scriptReader.Close();

            SqlCommand com = new SqlCommand(sql, new SqlConnection(connection));
            com.Connection.Open();
            com.ExecuteNonQuery();
            com.Connection.Close();
        }
    }
}